cd "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\"

global ETH "EthPanel-5.dta"
global GHN "GhaData-6.dta"
global MLW "MalPanel-5.dta"
global NGR "NigPanel-6.dta"
global TZN "TanPanel-5.dta"
global UGD "UgaPanel-6.dta"

************************************************************************
*PANEL
************************************************************************

*Beginning

use "$ETH", clear

rename ntl_mean_harm avg_radiance
gen oldclus = 0
*Farmsize blocks
generate blocks= irecode(farmsize, 0.25,1,3,5,50)
replace blocks=blocks+1
label def blocks 1 "0 - 0.25 ha" 2 "0.25 - 1 ha" 3 "1 - 3 ha" 4 "3 - 5 ha" 5 "> 5 ha"
label val blocks blocks 
tab blocks, g(bl)
tab comcat
*Commercial (share sold production)
gen prop10=ccom>0.10
gen prop0=ccom>0.01
*droping non-farm households (do not meet the minimum 0.25 ha threshold) 
*drop if bl1==1
*Interaction terms
for var bl1 bl2 bl3 bl4 bl5: gen IX=X*prop10
*Commercial categories
generate comm_gr= irecode(ccom, 0.05,0.2,0.5,1)
replace comm_gr=comm_gr+1
label def comm_gr 1 "Non-commercial" 2 "Barely commercial" 3 "Moderate commercial" 4 "Fully commercial"
label val comm_gr comm_gr 
*Commercial typology
gen 	commercialG=1 if ccom<=0.05             & NonfIncShare<=1/3
replace commercialG=2 if inrange(ccom,0.05,0.5) & NonfIncShare<=1/3
replace commercialG=3 if inrange(ccom,0.5,1)    & NonfIncShare<=1/3
replace commercialG=4 if inrange(ccom,0.05,0.5) & NonfIncShare>1/3
replace commercialG=5 if inrange(ccom,0.5,1)    & NonfIncShare>1/3
label def commercialG 1 "Subsistence" 2 "Pre-commercial" 3 "Specializing commercial" 4 "Transitioning" 5 "Diversified"
label val commercialG commercialG 
*Productivity
gen value_ha=ln((vh+1)/farmsize)
gen lnfarmsize=ln(farmsize)
egen cll=group(cl)
egen idd=group(id)
global cont "agehead female ac_headeduc dependency_ratio lnfarmsize hhsize NonfIncShare overall_shock"
keep idd t cll $cont farmsize bl1 bl2 bl3 bl4 bl5 Ibl1 Ibl2 Ibl3 Ibl4 Ibl5 ccom comcat prop0 prop10 comm_gr commercialG blocks value_ha poor mpi_poor rci FCS emp cluster_alt road_density avg_radiance incindex2 participate  Netnfcashinc treat1 ac_ent ac_workforce incindex3 poor2 SSP line  ezone favzone cluster_dist quint trader cci cpw zone ac_salaried agro2d agro3d oldclus
order idd t cll $cont farmsize bl1 bl2 bl3 bl4 bl5 Ibl1 Ibl2 Ibl3 Ibl4 Ibl5 ccom comcat prop0 prop10 comm_gr commercialG blocks value_ha poor mpi_poor rci FCS emp cluster_alt road_density avg_radiance incindex2 participate  Netnfcashinc treat1 ac_ent ac_workforce incindex3 poor2 line  ezone favzone SSP cluster_dist quint trader cci cpw zone  ac_salaried agro2d agro3d
drop if idd==.
destring avg_radiance, replace
replace avg_radiance=0 if avg_radiance<0
gen Dcluster_alt=., a(oldclus)
foreach num of numlist 1/3 {
summ oldclus if t==`num'
replace Dcluster_alt=1 if oldclus>=r(mean)+r(sd) & t==`num'
replace Dcluster_alt=0 if oldclus<r(mean)+r(sd) & t==`num'
replace Dcluster_alt=. if oldclus==. & t==`num'
}
gen Davg_radiance=., a(avg_radiance)
foreach num of numlist 2/4 {
summ avg_radiance if t==`num'
replace Davg_radiance=1 if avg_radiance>=r(mean)+r(sd) & t==`num'
replace Davg_radiance=0 if avg_radiance<r(mean)+r(sd) & t==`num'
replace avg_radiance=. if avg_radiance==. & t==`num'
}

gen country="ETH", a(cll)
tempfile rr1
save `rr1'
 



use "$GHN", clear 
gen oldclus = 0
drop avg_radiance
rename ntl_mean_harm avg_radiance
generate blocks= irecode(farmsize, 0.25,1,3,5,50)
replace blocks=blocks+1
label def blocks 1 "0 - 0.25 ha" 2 "0.25 - 1 ha" 3 "1 - 3 ha" 4 "3 - 5 ha" 5 "> 5 ha"
label val blocks blocks 
tab blocks, g(bl)
tab comcat
*Commercial (share sold production)
gen prop10=ccom>0.10
gen prop0=ccom>0.01
*droping non-farm households (do not meet the minimum 0.25 ha threshold) 
*drop if blocks==1
*Interaction terms
for var bl1 bl2 bl3 bl4 bl5: gen IX=X*prop10
*Commercial categories
generate comm_gr= irecode(ccom, 0.05,0.2,0.5,1)
replace comm_gr=comm_gr+1
label def comm_gr 1 "Non-commercial" 2 "Barely commercial" 3 "Moderate commercial" 4 "Fully commercial"
label val comm_gr comm_gr 
*Commercial typology
gen 	commercialG=1 if ccom<=0.05             & NonfIncShare<=1/3
replace commercialG=2 if inrange(ccom,0.05,0.5) & NonfIncShare<=1/3
replace commercialG=3 if inrange(ccom,0.5,1)    & NonfIncShare<=1/3
replace commercialG=4 if inrange(ccom,0.05,0.5) & NonfIncShare>1/3
replace commercialG=5 if inrange(ccom,0.5,1)    & NonfIncShare>1/3
label def commercialG 1 "Subsistence" 2 "Pre-commercial" 3 "Specializing commercial" 4 "Transitioning" 5 "Diversified"
label val commercialG commercialG 
*Productivity
gen value_ha=ln((vh+1)/farmsize)
gen lnfarmsize=ln(farmsize)
egen cll=group(clust)
gen rci=rci_norm
gen FCS = rci
global cont "agehead female ac_headeduc dependency_ratio lnfarmsize hhsize NonfIncShare"
drop idd
egen idd=group(id)
drop if idd==.
keep idd t cll $cont farmsize bl1 bl2 bl3 bl4 bl5 Ibl1 Ibl2 Ibl3 Ibl4 Ibl5 ccom comcat prop0 prop10 comm_gr commercialG blocks value_ha poor mpi_poor rci FCS emp cluster_alt road_density avg_radiance incindex2 participate  Netnfcashinc treat1 ac_ent ac_workforce incindex3 poor2 line  ezone favzone SSP quint trader cci weight  ac_salaried agro2d agro3d oldclus
order idd t cll $cont farmsize bl1 bl2 bl3 bl4 bl5 Ibl1 Ibl2 Ibl3 Ibl4 Ibl5 ccom comcat prop0 prop10 comm_gr commercialG blocks value_ha poor mpi_poor rci FCS emp cluster_alt road_density avg_radiance incindex2 participate  Netnfcashinc treat1 ac_ent ac_workforce incindex3 poor2 line  ezone favzone SSP quint trader cci weight  ac_salaried agro2d agro3d
destring road_density avg_radiance, replace
gen Dcluster_alt=., a(oldclus)
foreach num of numlist 2/5 {
summ oldclus if t==`num'
replace Dcluster_alt=1 if oldclus>=r(mean)+r(sd) & t==`num'
replace Dcluster_alt=0 if oldclus<r(mean)+r(sd) & t==`num'
replace Dcluster_alt=. if oldclus==. & t==`num'
}
gen Davg_radiance=., a(avg_radiance)
foreach num of numlist 5 {
summ avg_radiance if t==`num'
replace Davg_radiance=1 if avg_radiance>=r(mean)+(r(sd)*0.5) & t==`num'
replace Davg_radiance=0 if avg_radiance<r(mean)+(r(sd)*0.5) & t==`num'
replace avg_radiance=. if avg_radiance==. & t==`num'
}

gen country="GHN", a(cll)
tempfile rr2
save `rr2'

use "$MLW", clear 
gen oldclus = 0

rename ntl_mean_harm avg_radiance

tostring case_id, replace force format(%32.0g)

merge m:m case_id using "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\Malawi\Malawi\Malawi\Malawi 2010-2019\MWI_2010-2019_IHPS_v04_M_Stata\hh_mod_a_filt_10.dta", keepusing(hh_a01 hh_a02b)

rename district district2 
rename hh_a02b district

tostring district, replace force
drop _merge
*merge m:1 district using "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Cluster\Malawi_CI_TAlevel.dta"

*drop if _merge == 2
*drop _merge

*gen cluster_dist = .
*replace cluster_dist = cid_10 if t == 1
*replace cluster_dist = cid_13 if t == 2
*replace cluster_dist = cid_19 if t == 4
*Farmsize blocks
generate blocks= irecode(farmsize, 0.25,1,3,5,50)
replace blocks=blocks+1
label def blocks 1 "0 - 0.25 ha" 2 "0.25 - 1 ha" 3 "1 - 3 ha" 4 "3 - 5 ha" 5 "> 5 ha"
label val blocks blocks 
tab blocks, g(bl)
tab comcat
*Commercial (share sold production)
gen prop10=ccom>0.10
gen prop0=ccom>0.01
*droping non-farm households (do not meet the minimum 0.25 ha threshold) 
*drop if bl1==1
*Interaction terms
for var bl1 bl2 bl3 bl4 bl5: gen IX=X*prop10
*Commercial categories
generate comm_gr= irecode(ccom, 0.05,0.2,0.5,1)
replace comm_gr=comm_gr+1
label def comm_gr 1 "Non-commercial" 2 "Barely commercial" 3 "Moderate commercial" 4 "Fully commercial"
label val comm_gr comm_gr 
*Commercial typology
gen 	commercialG=1 if ccom<=0.05             & NonfIncShare<=1/3
replace commercialG=2 if inrange(ccom,0.05,0.5) & NonfIncShare<=1/3
replace commercialG=3 if inrange(ccom,0.5,1)    & NonfIncShare<=1/3
replace commercialG=4 if inrange(ccom,0.05,0.5) & NonfIncShare>1/3
replace commercialG=5 if inrange(ccom,0.5,1)    & NonfIncShare>1/3
label def commercialG 1 "Subsistence" 2 "Pre-commercial" 3 "Specializing commercial" 4 "Transitioning" 5 "Diversified"
label val commercialG commercialG 
*Productivity
gen value_ha=ln((vh+1)/farmsize)
gen lnfarmsize=ln(farmsize)

egen cll=group(cl)
drop idd
egen idd=group(id)


global cont "agehead female ac_headeduc dependency_ratio lnfarmsize hhsize NonfIncShare overall_shock"
drop poor2 line
gen poor2=poor
gen line=poor
keep idd t cll $cont farmsize bl1 bl2 bl3 bl4 bl5 Ibl1 Ibl2 Ibl3 Ibl4 Ibl5 ccom comcat prop0 prop10 comm_gr commercialG blocks value_ha poor mpi_poor rci FCS emp cluster_alt road_density avg_radiance  incindex2 participate  Netnfcashinc treat1 ac_ent ac_workforce incindex3 poor2 line  ezone favzone SSP cluster_dist  quint trader cci cpw district  ac_salaried agro2d agro3d oldclus
order idd t cll $cont farmsize bl1 bl2 bl3 bl4 bl5 Ibl1 Ibl2 Ibl3 Ibl4 Ibl5 ccom comcat prop0 prop10 comm_gr commercialG blocks value_ha poor mpi_poor rci FCS emp cluster_alt road_density avg_radiance incindex2 participate  Netnfcashinc treat1 ac_ent ac_workforce incindex3 poor2 line  ezone favzone SSP cluster_dist  quint trader cci cpw district  ac_salaried agro2d agro3d
destring  avg_radiance, replace
drop if idd==.

gen Dcluster_alt=., a(oldclus)
foreach num of numlist 1 2 4 {
summ oldclus if t==`num'
replace Dcluster_alt=1 if oldclus>=r(mean)+r(sd) & t==`num'
replace Dcluster_alt=0 if oldclus<r(mean)+r(sd) & t==`num'
replace Dcluster_alt=. if oldclus==. & t==`num'
}
gen Davg_radiance=., a(avg_radiance)
foreach num of numlist 3/4 {
summ avg_radiance if t==`num'
replace Davg_radiance=1 if avg_radiance>=r(mean)+(r(sd)*0.5) & t==`num'
replace Davg_radiance=0 if avg_radiance<r(mean)+(r(sd)*0.5) & t==`num'
replace avg_radiance=. if avg_radiance==. & t==`num'
}

destring district, replace

gen country="MLW", a(cll)
tempfile rr3
save `rr3'

use "$NGR", clear 
*Farmsize blocks
gen oldclus = 0
rename ntl_mean_harm avg_radiance


generate blocks= irecode(farmsize, 0.25,1,3,5,50)
replace blocks=blocks+1
label def blocks 1 "0 - 0.25 ha" 2 "0.25 - 1 ha" 3 "1 - 3 ha" 4 "3 - 5 ha" 5 "> 5 ha"
label val blocks blocks 
tab blocks, g(bl)
tab comcat
*Commercial (share sold production)
gen prop10=ccom>0.10
gen prop0=ccom>0.01
*droping non-farm households (do not meet the minimum 0.25 ha threshold) 
*drop if bl1==1
*Interaction terms
for var bl1 bl2 bl3 bl4 bl5: gen IX=X*prop10
*Commercial categories
generate comm_gr= irecode(ccom, 0.05,0.2,0.5,1)
replace comm_gr=comm_gr+1
label def comm_gr 1 "Non-commercial" 2 "Barely commercial" 3 "Moderate commercial" 4 "Fully commercial"
label val comm_gr comm_gr 
*Commercial typology
gen 	commercialG=1 if ccom<=0.05             & NonfIncShare<=1/3
replace commercialG=2 if inrange(ccom,0.05,0.5) & NonfIncShare<=1/3
replace commercialG=3 if inrange(ccom,0.5,1)    & NonfIncShare<=1/3
replace commercialG=4 if inrange(ccom,0.05,0.5) & NonfIncShare>1/3
replace commercialG=5 if inrange(ccom,0.5,1)    & NonfIncShare>1/3
label def commercialG 1 "Subsistence" 2 "Pre-commercial" 3 "Specializing commercial" 4 "Transitioning" 5 "Diversified"
label val commercialG commercialG 
*Productivity
gen value_ha=ln((vh+1)/farmsize)
gen lnfarmsize=ln(farmsize)
egen cll=group(cl)
drop idd
egen idd=group(id)
global cont "agehead female ac_headeduc dependency_ratio lnfarmsize hhsize NonfIncShare overall_shock"
keep idd t cll $cont farmsize bl1 bl2 bl3 bl4 bl5 Ibl1 Ibl2 Ibl3 Ibl4 Ibl5 ccom comcat prop0 prop10 comm_gr commercialG blocks value_ha poor mpi_poor rci FCS emp cluster_alt road_density avg_radiance incindex2 participate Netnfcashinc treat1 ac_ent ac_workforce incindex3 poor2 line  ezone favzone SSP cluster_dist quint trader cci cpw lga  ac_salaried agro2d agro3d oldclus
order idd t cll $cont farmsize bl1 bl2 bl3 bl4 bl5 Ibl1 Ibl2 Ibl3 Ibl4 Ibl5 ccom comcat prop0 prop10 comm_gr commercialG blocks value_ha poor mpi_poor rci FCS emp cluster_alt road_density avg_radiance incindex2 participate Netnfcashinc treat1 ac_ent ac_workforce incindex3 poor2 line  ezone favzone SSP cluster_dist quint trader cci cpw lga  ac_salaried agro2d agro3d
destring  avg_radiance, replace
drop if idd==.

gen Dcluster_alt=., a(oldclus)
foreach num of numlist 1/4 {
summ oldclus if t==`num'
replace Dcluster_alt=1 if oldclus>=r(mean)+r(sd) & t==`num'
replace Dcluster_alt=0 if oldclus<r(mean)+r(sd) & t==`num'
replace Dcluster_alt=. if oldclus==. & t==`num'
}
gen Davg_radiance=., a(avg_radiance)
foreach num of numlist 3/4 {
summ avg_radiance if t==`num'
replace Davg_radiance=1 if avg_radiance>=r(mean)+(r(sd)*0.5) & t==`num'
replace Davg_radiance=0 if avg_radiance<r(mean)+(r(sd)*0.5) & t==`num'
replace avg_radiance=. if avg_radiance==. & t==`num'
}

gen country="NGR", a(cll)
tempfile rr4
save `rr4'

use "$TZN", clear 
drop avg_radiance
rename ntl_mean_harm avg_radiance
gen oldclus = 0
*Farmsize blocks
generate blocks= irecode(farmsize, 0.25,1,3,5,50)
replace blocks=blocks+1
label def blocks 1 "0 - 0.25 ha" 2 "0.25 - 1 ha" 3 "1 - 3 ha" 4 "3 - 5 ha" 5 "> 5 ha"
label val blocks blocks 
tab blocks, g(bl)
tab comcat
*Commercial (share sold production)
gen prop10=ccom>0.10
gen prop0=ccom>0.01
*droping non-farm households (do not meet the minimum 0.25 ha threshold) 
*drop if bl1==1
*Interaction terms
for var bl1 bl2 bl3 bl4 bl5: gen IX=X*prop10
*Commercial categories
generate comm_gr= irecode(ccom, 0.05,0.2,0.5,1)
replace comm_gr=comm_gr+1
label def comm_gr 1 "Non-commercial" 2 "Barely commercial" 3 "Moderate commercial" 4 "Fully commercial"
label val comm_gr comm_gr 
*Commercial typology
gen 	commercialG=1 if ccom<=0.05             & NonfIncShare<=1/3
replace commercialG=2 if inrange(ccom,0.05,0.5) & NonfIncShare<=1/3
replace commercialG=3 if inrange(ccom,0.5,1)    & NonfIncShare<=1/3
replace commercialG=4 if inrange(ccom,0.05,0.5) & NonfIncShare>1/3
replace commercialG=5 if inrange(ccom,0.5,1)    & NonfIncShare>1/3
label def commercialG 1 "Subsistence" 2 "Pre-commercial" 3 "Specializing commercial" 4 "Transitioning" 5 "Diversified"
label val commercialG commercialG 
*Productivity
gen value_ha=ln((vh+1)/farmsize)
gen lnfarmsize=ln(farmsize)
egen cll=group(cl)
egen idd=group(id)
gen idd2=idd
replace idd=idd+5000 if inlist(t,4,5)
global cont "agehead female ac_headeduc dependency_ratio lnfarmsize hhsize NonfIncShare overall_shock"
keep idd t cll $cont farmsize bl1 bl2 bl3 bl4 bl5 Ibl1 Ibl2 Ibl3 Ibl4 Ibl5 ccom comcat prop0 prop10 comm_gr commercialG blocks value_ha poor mpi_poor rci FCS emp cluster_alt road_density avg_radiance idd2 incindex2 participate  Netnfcashinc treat1 ac_ent ac_workforce incindex3 poor2 line  ezone favzone SSP cluster_dist quint trader cci cpw district ac_salaried agro2d agro3d oldclus
order idd t cll $cont farmsize bl1 bl2 bl3 bl4 bl5 Ibl1 Ibl2 Ibl3 Ibl4 Ibl5 ccom comcat prop0 prop10 comm_gr commercialG blocks value_ha poor mpi_poor rci FCS emp cluster_alt road_density avg_radiance incindex2 participate  Netnfcashinc treat1 ac_ent ac_workforce incindex3 poor2 line  ezone favzone SSP cluster_dist quint trader cci cpw district ac_salaried agro2d agro3d
destring  avg_radiance, replace
drop if idd==.
replace cluster_alt=. if t==3

gen Dcluster_alt=., a(oldclus)
foreach num of numlist 4/5 {
summ oldclus if t==`num'
replace Dcluster_alt=1 if oldclus>=r(mean)+r(sd) & t==`num'
replace Dcluster_alt=0 if oldclus<r(mean)+r(sd) & t==`num'
replace Dcluster_alt=. if oldclus==. & t==`num'
}
gen Davg_radiance=., a(avg_radiance)
foreach num of numlist 4/5 {
summ avg_radiance if t==`num'
replace Davg_radiance=1 if avg_radiance>=r(mean)+(r(sd)*0.5) & t==`num'
replace Davg_radiance=0 if avg_radiance<r(mean)+(r(sd)*0.5) & t==`num'
replace avg_radiance=. if avg_radiance==. & t==`num'
}

gen country="TZN", a(cll)
tempfile rr5
save `rr5'

use "$UGD", clear 
gen oldclus = 0
drop avg_radiance
rename ntl_mean_harm avg_radiance

*Farmsize blocks
rename cindex ci4
generate blocks= irecode(farmsize, 0.25,1,3,5,50)
replace blocks=blocks+1
label def blocks 1 "0 - 0.25 ha" 2 "0.25 - 1 ha" 3 "1 - 3 ha" 4 "3 - 5 ha" 5 "> 5 ha"
label val blocks blocks 
tab blocks, g(bl)
tab comcat
*Commercial (share sold production)
gen prop10=ccom>0.10
gen prop0=ccom>0.01
*droping non-farm households (do not meet the minimum 0.25 ha threshold) 
*drop if bl1==1
*Interaction terms
for var bl1 bl2 bl3 bl4 bl5: gen IX=X*prop10
*Commercial categories
generate comm_gr= irecode(ccom, 0.05,0.2,0.5,1)
replace comm_gr=comm_gr+1
label def comm_gr 1 "Non-commercial" 2 "Barely commercial" 3 "Moderate commercial" 4 "Fully commercial"
label val comm_gr comm_gr 
*Commercial typology
gen 	commercialG=1 if ccom<=0.05             & NonfIncShare<=1/3
replace commercialG=2 if inrange(ccom,0.05,0.5) & NonfIncShare<=1/3
replace commercialG=3 if inrange(ccom,0.5,1)    & NonfIncShare<=1/3
replace commercialG=4 if inrange(ccom,0.05,0.5) & NonfIncShare>1/3
replace commercialG=5 if inrange(ccom,0.5,1)    & NonfIncShare>1/3
label def commercialG 1 "Subsistence" 2 "Pre-commercial" 3 "Specializing commercial" 4 "Transitioning" 5 "Diversified"
label val commercialG commercialG 
*Productivity
gen value_ha=ln((qs+1)/farmsize)
gen lnfarmsize=ln(farmsize)
egen cll=group(cl)
egen idd=group(id)
global cont "agehead female ac_headeduc dependency_ratio lnfarmsize hhsize NonfIncShare overall_shock"
keep idd t cll $cont farmsize bl1 bl2 bl3 bl4 bl5 Ibl1 Ibl2 Ibl3 Ibl4 Ibl5 ccom comcat prop0 prop10 comm_gr commercialG blocks value_ha poor mpi_poor rci FCS emp cluster_alt road_density avg_radiance incindex2 participate  Netnfcashinc treat1 ac_ent ac_workforce incindex3 poor2 line  ezone favzone SSP cluster_dist quint trader cci cpw district ac_salaried agro2d agro3d oldclus
order idd t cll $cont farmsize bl1 bl2 bl3 bl4 bl5 Ibl1 Ibl2 Ibl3 Ibl4 Ibl5 ccom comcat prop0 prop10 comm_gr commercialG blocks value_ha poor mpi_poor rci FCS emp cluster_alt road_density avg_radiance incindex2 participate  Netnfcashinc treat1 ac_ent ac_workforce incindex3 poor2 line  ezone favzone SSP cluster_dist quint trader cci cpw district ac_salaried agro2d agro3d
destring  avg_radiance, replace
drop if idd==.
gen Dcluster_alt=., a(oldclus)
foreach num of numlist 1/5 {
summ oldclus if t==`num'
replace Dcluster_alt=1 if oldclus>=r(mean)+r(sd) & t==`num'
replace Dcluster_alt=0 if oldclus<r(mean)+r(sd) & t==`num'
replace Dcluster_alt=. if oldclus==. & t==`num'
}
gen Davg_radiance=., a(avg_radiance)
foreach num of numlist 3/5 {
summ avg_radiance if t==`num'
replace Davg_radiance=1 if avg_radiance>=r(mean)+(r(sd)*0.5) & t==`num'
replace Davg_radiance=0 if avg_radiance<r(mean)+(r(sd)*0.5) & t==`num'
replace avg_radiance=. if avg_radiance==. & t==`num'
}

gen country="UGD", a(cll)
tempfile rr6
save `rr6'

clear
foreach nn of numlist 1/6 {
append using `rr`nn''
}
bys country idd (t): egen nrounds=count(t) 
gen panel=nrounds!=1
replace Davg_radiance=. if avg_radiance==.
replace Dcluster_alt=. if cluster_alt==.

gen sell_msme=(treat1==1 | ac_ent==1)
replace  sell_msme=. if treat1==. & ac_ent==.
gen Netnfcashinc_pc=Netnfcashinc/hhsize
gen lnNetnfcashinc=ln(Netnfcashinc+1)
gen lnNetnfcashinc_pc=ln(Netnfcashinc_pc+1)
order Netnfcashinc_pc-lnNetnfcashinc_pc, a(Netnfcashinc)
gen lnavg_radiance=ln(avg_radiance+1)
gen lnroad_density=ln(road_density+1)
gen farmsize2=(farmsize^2)
gen lnfarmsize2=ln(farmsize^2)

save "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", replace

*end




************************************************************************
*TABLE 2
************************************************************************
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear


foreach cc in "ETH" "MLW" "TZN" "UGD" "NGR" "GHN" {
    preserve
	keep if country=="`cc'"
	* Check if variable cpw exists; if not, create it as a copy of weight
	* 1. Check if cpw exists
	capture confirm variable cpw
	if _rc {
		* cpw does not exist, create it
		gen cpw = weight
	}
	else {
		* cpw exists; check if all values are missing
		quietly count if !missing(cpw)
		if r(N) == 0 {
			drop cpw
			gen cpw = weight
		}
	}

	keep if SSP == 1
	svyset [pw=cpw]
	cap drop treat1
	gen treat1 = cci > 0 & cci != .
	gen both = ac_ent == 1 | treat1 == 1
	svy: mean treat1 ac_ent both
	svy: mean cci if cci > 0 & cci != .
	restore
}




************************************************************************
*TABLE 3
************************************************************************
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear


foreach cc in "ETH" "MLW" "TZN" "UGD" "NGR" "GHN" {
    preserve
	keep if country=="`cc'"
	* Check if variable cpw exists; if not, create it as a copy of weight
	* 1. Check if cpw exists
	capture confirm variable cpw
	if _rc {
		* cpw does not exist, create it
		gen cpw = weight
	}
	else {
		* cpw exists; check if all values are missing
		quietly count if !missing(cpw)
		if r(N) == 0 {
			drop cpw
			gen cpw = weight
		}
	}
	keep if SSP == 1
	summ rci, meanonly
	gen rci_norm = (rci - r(min)) / (r(max) - r(min))

	gen has_offarm = Netnfcashinc > 0 & Netnfcashinc != .
	svyset [pw=cpw]
	svy: mean FCS rci_norm emp if t != 1
	svy: mean has_offarm poor2 agehead female ac_workforce dependency_ratio hhsize NonfIncShare farmsize 
	svy: mean cluster_alt road_density avg_radiance
	restore
}



************************************************************************
*TABLE 4
************************************************************************

*z-scores
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear
global clust 	"cll"
global idd 		"idd"
drop if inlist(t,1,2,3) & country=="TZN"

drop treat1 
gen treat1 = 0
replace treat1 = 1 if cci > 0 & cci !=.

capture confirm variable sell_msme
if !_rc drop sell_msme


capture confirm variable farmsize2
if !_rc drop farmsize2


gen sell_msme=(treat1==1 | ac_ent==1)
replace  sell_msme=. if treat1==. & ac_ent==.
gen farmsize2 = farmsize*farmsize

global cont "agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare overall_shock road_density"
global out "incindex3"	
foreach var of varlist sell_msme {
foreach cc in "ETH" "MLW" "NGR" "TZN" "UGD" {
    preserve
	keep if country=="`cc'"
	summ incindex3
	replace incindex3=(incindex3-r(mean))/(r(sd))
	reghdfe $out `var' $cont, absorb($idd t ) vce(cluster $idd)
	outreg2 using "resultsnew.xml", excel bdec(3) append ///
	addtext(Household FE, Yes, Year of survey FE, Yes, Cluster SE at the household-level, Yes, ///
	Number of clusters,`e(N_clust)', adjusted r2, `e(r2_a)',adjusted within r2,`e(r2_a_within)')
	sleep 500
	restore
}
}
 * Now Ghana cross-section 
global cont2 "agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare road_density"
foreach var of varlist sell_msme {
foreach cc in "GHN" {
	preserve
	keep if country=="`cc'"
	summ incindex3
	replace incindex3=(incindex3-r(mean))/(r(sd))
	reghdfe $out `var' $cont2, absorb($clust t ) vce(cluster $clust)
	outreg2 using "resultsnew2.xml", excel bdec(3) append ///
	addtext(Household FE, Yes, Year of survey FE, Yes, Cluster SE at the household-level, No, ///
	Number of clusters,`e(N_clust)', adjusted r2, `e(r2_a)',adjusted within r2,`e(r2_a_within)')
	sleep 500
	restore
}
}



********************************
****** Table  5 ****************
********************************
*z-scores
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear
global clust 	"cll"
global idd 		"idd"
drop if inlist(t,1,2,3) & country=="TZN"

drop treat1 
gen treat1 = 0
replace treat1 = 1 if cci > 0 & cci !=.

capture confirm variable sell_msme
if !_rc drop sell_msme


capture confirm variable farmsize2
if !_rc drop farmsize2


gen sell_msme=(treat1==1 | ac_ent==1)
replace  sell_msme=. if treat1==. & ac_ent==.
gen farmsize2 = farmsize*farmsize



** Interaction with cluster index

global cont "agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare overall_shock road_density"
global out "incindex3"	
foreach var of varlist sell_msme {
foreach cc in "ETH" "MLW" "NGR" "TZN" "UGD" {
    preserve
	keep if country=="`cc'"
	summ incindex3
	replace incindex3=(incindex3-r(mean))/(r(sd))
	reghdfe $out i.sell_msme##c.cluster_alt $cont, absorb($idd t ) vce(cluster $idd)
	outreg2 using "table5.xml", excel bdec(3) append ///
	addtext(Household FE, Yes, Year of survey FE, Yes, Cluster SE at the household-level, Yes, ///
	Number of clusters,`e(N_clust)', adjusted r2, `e(r2_a)',adjusted within r2,`e(r2_a_within)')
	sleep 500
	restore
}
}

** Interaction with nighttime lights 

foreach var of varlist sell_msme {
foreach cc in "ETH" "MLW" "NGR" "TZN" "UGD" {
    preserve
	keep if country=="`cc'"
	summ incindex3
	replace incindex3=(incindex3-r(mean))/(r(sd))
	reghdfe $out i.sell_msme##c.avg_radiance $cont, absorb($idd t ) vce(cluster $idd)
	outreg2 using "table5-radiance.xml", excel bdec(3) append ///
	addtext(Household FE, Yes, Year of survey FE, Yes, Cluster SE at the household-level, Yes, ///
	Number of clusters,`e(N_clust)', adjusted r2, `e(r2_a)',adjusted within r2,`e(r2_a_within)')
	sleep 500
	restore
}
}





********************************
****** Table  6 ****************
********************************
*z-scores
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear
global clust 	"cll"
global idd 		"idd"
drop if inlist(t,1,2,3) & country=="TZN"

drop treat1 
gen treat1 = 0
replace treat1 = 1 if cci > 0 & cci !=.

capture confirm variable sell_msme
if !_rc drop sell_msme


capture confirm variable farmsize2
if !_rc drop farmsize2


gen sell_msme=(treat1==1 | ac_ent==1)
replace  sell_msme=. if treat1==. & ac_ent==.
gen farmsize2 = farmsize*farmsize



** Panel A

global cont "agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare overall_shock road_density"
global out "incindex3"	
foreach var of varlist sell_msme {
foreach cc in "ETH" "MLW" "NGR" "TZN" "UGD" {
    preserve
	keep if country=="`cc'"
	summ incindex3
	replace incindex3=(incindex3-r(mean))/(r(sd))
	reghdfe $out sell_msme $cont, absorb($idd t ) vce(cluster $idd)
	outreg2 using "table6panela.xml", excel bdec(3) append ///
	addtext(Household FE, Yes, Year of survey FE, Yes, Cluster SE at the household-level, Yes, ///
	Number of clusters,`e(N_clust)', adjusted r2, `e(r2_a)',adjusted within r2,`e(r2_a_within)')
	sleep 500
	restore
}
}

** Panel B & C

global cont "agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare overall_shock road_density"
global out "incindex3"	
foreach var of varlist sell_msme {
foreach cc in "ETH" "MLW" "NGR" "TZN" "UGD" {
    preserve
	keep if country=="`cc'"
	summ incindex3
	replace incindex3=(incindex3-r(mean))/(r(sd))
	ivreghdfe $out (sell_msme = cluster_alt) $cont, absorb($idd t ) vce(cluster $idd) endog(sell_msme) first
	outreg2 using "table6panelb.xml", excel bdec(3) append ///
	addtext(Household FE, Yes, Year of survey FE, Yes, Cluster SE at the household-level, Yes, ///
	Number of clusters,`e(N_clust)', adjusted r2, `e(r2_a)',adjusted within r2,`e(r2_a_within)')
	sleep 500
	restore
}
}




************************************************************************
* Appendix Table B1 B2
************************************************************************
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear


foreach cc in "ETH" "MLW" "TZN" "UGD" "NGR" "GHN" {
    preserve
	keep if country=="`cc'"
	* Check if variable cpw exists; if not, create it as a copy of weight
	* 1. Check if cpw exists
	capture confirm variable cpw
	if _rc {
		* cpw does not exist, create it
		gen cpw = weight
	}
	else {
		* cpw exists; check if all values are missing
		quietly count if !missing(cpw)
		if r(N) == 0 {
			drop cpw
			gen cpw = weight
		}
	}

	keep if SSP == 1
	svyset [pw=cpw]
	cap drop treat1
	gen treat1 = cci > 0 & cci != .
	gen both = ac_ent == 1 | treat1 == 1
	svy: mean treat1 both, over(t)
	restore
}




************************************************************************
* Appendix Table C1
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear
drop if inlist(t,1,2,3) & country=="TZN"

global idd   "idd"
global clust "cll"

* Candidate controls (some may be absent in some countries)
local cont_candidates agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare road_dense

* Countries and outcomes
local countries ETH MLW NGR TZN UGD GHN
local outcomes  poor2 rci FCS emp incindex3 lnNetnfcashinc_pc

* Pre-allocate (6 outcomes × 6 countries)
matrix W = J(36,4,.)   // col1 = row id; col2 = coef; col3 = lower; col4 = upper
local i = 1

foreach out of local outcomes {
    cap confirm variable `out'
    if _rc {
        di as err "Skipping outcome `out' (not found in the dataset)."
        forvalues k = 1/6 {
            matrix W[`i',1] = `i'
            matrix W[`i',2] = .
            matrix W[`i',3] = .
            matrix W[`i',4] = .
            local ++i
        }
        continue
    }

    foreach cc of local countries {
        preserve
            keep if country=="`cc'"

            * Build controls that exist AND vary in this subset
            local CONT
            foreach c of local cont_candidates {
                cap confirm variable `c'
                if !_rc {
                    quietly summarize `c'
                    if r(N)>1 & r(sd)>0 local CONT `CONT' `c'
                }
            }

            * Safely z-score the outcome
            quietly summarize `out'
            if r(N)>1 & r(sd)>0 {
                replace `out' = (`out' - r(mean)) / r(sd)
            }

            * Choose cluster + FE: Ghana uses clust if available, others use idd
            local absorb "$idd t"
            local clvar  "$idd"
            if "`cc'"=="GHN" {
                cap confirm variable $clust
                if !_rc {
                    local absorb "$clust t"
                    local clvar  "$clust"
                }
            }

            * Run regression (graceful failure -> missings)
            cap noisily reghdfe `out' sell_msme `CONT', absorb(`absorb') vce(cluster `clvar')
            if _rc {
                di as err "Note: `out' in `cc' failed (rc=`_rc'). Filling with missings."
                matrix W[`i',1] = `i'
                matrix W[`i',2] = .
                matrix W[`i',3] = .
                matrix W[`i',4] = .
            }
            else {
                local b  = _b[sell_msme]
                local se = _se[sell_msme]
                local tc = invttail(e(df_r), 0.025)
                matrix W[`i',1] = `i'
                matrix W[`i',2] = `b'
                matrix W[`i',3] = `b' - `tc'*`se'
                matrix W[`i',4] = `b' + `tc'*`se'
            }
            local ++i
        restore
    }
}


*****************************
***** Appendix Table C2 *****
*****************************


*z-scores
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear
global cll	"cll"
global idd 		"idd"
drop if inlist(t,1,2,3) & country=="TZN"

drop treat1 
gen treat1 = 0
replace treat1 = 1 if cci > 0 & cci !=.

capture confirm variable sell_msme
if !_rc drop sell_msme


capture confirm variable farmsize2
if !_rc drop farmsize2


gen sell_msme=(treat1==1 | ac_ent==1)
replace  sell_msme=. if treat1==. & ac_ent==.
gen farmsize2 = farmsize*farmsize



global cont "agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare overall_shock road_density"
global out "incindex3"	
foreach var of varlist sell_msme {
foreach cc in "ETH" "MLW" "NGR" "TZN" "UGD" {
    preserve
	keep if country=="`cc'"
	summ incindex3
	replace incindex3=(incindex3-r(mean))/(r(sd))
	reghdfe $out sell_msme $cont, absorb($idd t ) vce(cluster $idd)
	reghdfe $out treat1 $cont, absorb($idd t ) vce(cluster $idd)
	reghdfe $out ac_ent $cont, absorb($idd t ) vce(cluster $idd)
	reghdfe $out treat1 ac_ent $cont, absorb($idd t ) vce(cluster $idd)
	reghdfe $out cci $cont, absorb($idd t ) vce(cluster $idd)
	sleep 500
	restore
}
}

global cont "agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare road_density"
global out "incindex3"	
foreach var of varlist sell_msme {
foreach cc in "GHN" {
    preserve
	keep if country=="`cc'"
	summ incindex3
	replace incindex3=(incindex3-r(mean))/(r(sd))
	reghdfe $out sell_msme $cont, absorb($cll t ) vce(cluster $cll)
	reghdfe $out treat1 $cont, absorb($cll t ) vce(cluster $cll)
	reghdfe $out ac_ent $cont, absorb($cll t ) vce(cluster $cll)
	reghdfe $out treat1 ac_ent $cont, absorb($cll t ) vce(cluster $cll)
	reghdfe $out cci $cont, absorb($cll t ) vce(cluster $cll)
	sleep 500
	restore
}
}




********************************
****** Appendix Table C3 ****************
********************************
*z-scores
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear
global clust 	"cll"
global idd 		"idd"
drop if inlist(t,1,2,3) & country=="TZN"

drop treat1 
gen treat1 = 0
replace treat1 = 1 if cci > 0 & cci !=.

capture confirm variable sell_msme
if !_rc drop sell_msme


capture confirm variable farmsize2
if !_rc drop farmsize2


gen sell_msme=(treat1==1 | ac_ent==1)
replace  sell_msme=. if treat1==. & ac_ent==.
gen farmsize2 = farmsize*farmsize



** Interaction with cluster index

global cont "agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare overall_shock road_density"
global out "incindex3"	
foreach var of varlist sell_msme {
foreach cc in "ETH" "MLW" "NGR" "TZN" "UGD" {
    preserve
	keep if country=="`cc'"
	summ incindex3
	replace incindex3=(incindex3-r(mean))/(r(sd))
	reghdfe $out sell_msme $cont, absorb($idd t ) vce(cluster $idd)
	outreg2 using "tablec3.xml", excel bdec(3) append ///
	addtext(Household FE, Yes, Year of survey FE, Yes, Cluster SE at the household-level, Yes, ///
	Number of clusters,`e(N_clust)', adjusted r2, `e(r2_a)',adjusted within r2,`e(r2_a_within)')
	sleep 500
	restore
}
}




********************************
****** Appendix Table C4 ****************
********************************
*z-scores
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear
global clust 	"cll"
global idd 		"idd"
drop if inlist(t,1,2,3) & country=="TZN"

drop treat1 
gen treat1 = 0
replace treat1 = 1 if cci > 0 & cci !=.

capture confirm variable sell_msme
if !_rc drop sell_msme


capture confirm variable farmsize2
if !_rc drop farmsize2


gen sell_msme=(treat1==1 | ac_ent==1)
replace  sell_msme=. if treat1==. & ac_ent==.
gen farmsize2 = farmsize*farmsize



** Interaction with cluster index

global cont "agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare overall_shock road_density"
global out "incindex3"	
foreach var of varlist sell_msme {
foreach cc in "ETH" "MLW" "NGR" "TZN" "UGD" {
    preserve
	keep if country=="`cc'"
	summ incindex3
	replace incindex3=(incindex3-r(mean))/(r(sd))
	reghdfe $out i.sell_msme##c.cluster_dist $cont, absorb($idd t ) vce(cluster $idd)
	outreg2 using "tablec4.xml", excel bdec(3) append ///
	addtext(Household FE, Yes, Year of survey FE, Yes, Cluster SE at the household-level, Yes, ///
	Number of clusters,`e(N_clust)', adjusted r2, `e(r2_a)',adjusted within r2,`e(r2_a_within)')
	sleep 500
	restore
}
}



********************************
****** Appendix Table C5 ****************
********************************
*z-scores
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear
global clust 	"cll"
global idd 		"idd"
drop if inlist(t,1,2,3) & country=="TZN"

drop treat1 
gen treat1 = 0
replace treat1 = 1 if cci > 0 & cci !=.

capture confirm variable sell_msme
if !_rc drop sell_msme


capture confirm variable farmsize2
if !_rc drop farmsize2


gen sell_msme=(treat1==1 | ac_ent==1)
replace  sell_msme=. if treat1==. & ac_ent==.
gen farmsize2 = farmsize*farmsize



** Interaction with cluster index

global cont "agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare overall_shock road_density"
global out "incindex3"	
foreach var of varlist sell_msme {
foreach cc in "ETH" "MLW" "NGR" "TZN" "UGD" {
    preserve
	keep if country=="`cc'"
	summ incindex3
	replace incindex3=(incindex3-r(mean))/(r(sd))
	ivreghdfe $out (sell_msme=cluster_dist) $cont, absorb($idd t ) vce(cluster $idd) first
	sleep 500
	restore
}
}






********** FIGURES ***********
******************************

************************************************************************
* Figure 3 (z-scores) - SAME SCALE  — robust version
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear
drop if inlist(t,1,2,3) & country=="TZN"

global idd   "idd"
global clust "cll"

* Candidate controls (some may be absent in some countries)
local cont_candidates agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare road_dense

* Countries and outcomes
local countries ETH MLW NGR TZN UGD GHN
local outcomes  poor2 rci FCS emp incindex3 lnNetnfcashinc_pc

* Pre-allocate (6 outcomes × 6 countries)
matrix W = J(36,4,.)   // col1 = row id; col2 = coef; col3 = lower; col4 = upper
local i = 1

foreach out of local outcomes {
    cap confirm variable `out'
    if _rc {
        di as err "Skipping outcome `out' (not found in the dataset)."
        forvalues k = 1/6 {
            matrix W[`i',1] = `i'
            matrix W[`i',2] = .
            matrix W[`i',3] = .
            matrix W[`i',4] = .
            local ++i
        }
        continue
    }

    foreach cc of local countries {
        preserve
            keep if country=="`cc'"

            * Build controls that exist AND vary in this subset
            local CONT
            foreach c of local cont_candidates {
                cap confirm variable `c'
                if !_rc {
                    quietly summarize `c'
                    if r(N)>1 & r(sd)>0 local CONT `CONT' `c'
                }
            }

            * Safely z-score the outcome
            quietly summarize `out'
            if r(N)>1 & r(sd)>0 {
                replace `out' = (`out' - r(mean)) / r(sd)
            }

            * Choose cluster + FE: Ghana uses clust if available, others use idd
            local absorb "$idd t"
            local clvar  "$idd"
            if "`cc'"=="GHN" {
                cap confirm variable $clust
                if !_rc {
                    local absorb "$clust t"
                    local clvar  "$clust"
                }
            }

            * Run regression (graceful failure -> missings)
            cap noisily reghdfe `out' sell_msme `CONT', absorb(`absorb') vce(cluster `clvar')
            if _rc {
                di as err "Note: `out' in `cc' failed (rc=`_rc'). Filling with missings."
                matrix W[`i',1] = `i'
                matrix W[`i',2] = .
                matrix W[`i',3] = .
                matrix W[`i',4] = .
            }
            else {
                local b  = _b[sell_msme]
                local se = _se[sell_msme]
                local tc = invttail(e(df_r), 0.025)
                matrix W[`i',1] = `i'
                matrix W[`i',2] = `b'
                matrix W[`i',3] = `b' - `tc'*`se'
                matrix W[`i',4] = `b' + `tc'*`se'
            }
            local ++i
        restore
    }
}

* Materialize matrix -> vars
svmat W
rename W1 nn
rename W2 coef
rename W3 lower
rename W4 upper
keep nn coef lower upper
drop if missing(coef)   // <-- your original had "drop if nn==.", which never drops anything

* Country ids (based on original slots)
gen  country="ETH" if inlist(nn,1,7,13,19,25,31)
replace country="MLW" if inlist(nn,2,8,14,20,26,32)
replace country="NGR" if inlist(nn,3,9,15,21,27,33)
replace country="TZN" if inlist(nn,4,10,16,22,28,34)
replace country="UGD" if inlist(nn,5,11,17,23,29,35)
replace country="GHN" if inlist(nn,6,12,18,24,30,36)

gen  con=.
replace con=1 if inlist(nn,1,7,13,19,25,31)
replace con=2 if inlist(nn,2,8,14,20,26,32)
replace con=3 if inlist(nn,3,9,15,21,27,33)
replace con=4 if inlist(nn,4,10,16,22,28,34)
replace con=5 if inlist(nn,5,11,17,23,29,35)
replace con=6 if inlist(nn,6,12,18,24,30,36)
label def con 1 "ETH" 2 "MLW" 3 "NGR" 4 "TZN" 5 "UGD" 6 "GHN"
label val con con

* Variable panel ids (same mapping you used)
gen  var=.
replace var=1 if inrange(nn,1,6)
replace var=2 if inrange(nn,7,12)
replace var=3 if inrange(nn,13,18)
replace var=4 if inrange(nn,19,24)
replace var=6 if inrange(nn,25,30)
replace var=5 if inrange(nn,31,36)

label def var 1 "Consumption Poverty" 2 "Resilience Index" 3 "Food Consumption Score" 4 "Empowerment" 5 "Log non-farm p/c income" 6 "Inclusion Index"
label val var var

* === Plots (Inclusion Index first) =========================================
preserve
keep if var==6
twoway  (scatter con coef, m(circle) msize(small) mcolor(black) lw(medthick)) ///
        (rcap upper lower con, lw(medthin) lcolor(black) msize(medium) horizontal), ///
        xtitle("Coefficient", margin(small) size(*1)) ///
        ytitle(" ", margin(vvsmall) size(*0.8)) ///
        legend(symplacement(north) rows(1) size(small) position(12) ring(1)) ///
        xline(0, lcolor(cranberry)) ///
        xlabel(-0.2(0.1)0.7, labsize(vsmall) format(%2.1f)) ///
        ylabel(, labsize(small) valuelabel) ///
        yscale(range(0.5 5.5)) ///
        xscale(range(-.2 0.71)) ///
        scheme(tab2) xsize(5.5) ysize(3.5) ///
        legend(order(1 "Coefficient" 2 "Upper/Lower 95% CI")) ///
        title("Inclusion Index") saving("F1.gph", replace)
restore

preserve
keep if var==1
twoway  (scatter con coef, m(circle) msize(small) mcolor(blue%98) lw(medthick)) ///
        (rcap upper lower con, lw(medthin) lcolor(blue%98) msize(medium) horizontal), ///
        xtitle("Coefficient", margin(small) size(*1)) ///
        ytitle(" ", margin(vvsmall) size(*0.8)) ///
        legend(symplacement(north) rows(1) size(small) position(12) ring(1)) ///
        xline(0, lcolor(cranberry)) ///
        xlabel(-0.2(0.1)0.7, labsize(vsmall) format(%2.1f)) ///
        ylabel(, labsize(small) valuelabel) ///
        yscale(range(0.5 6.5)) ///
        xscale(range(-.2 0.71)) ///
        scheme(tab2) xsize(5.5) ysize(3.5) ///
        legend(order(1 "Coefficient" 2 "Upper/Lower 95% CI")) ///
        title("Consumption Poverty") saving("F2.gph", replace)
restore

preserve
keep if var==2
twoway  (scatter con coef, m(circle) msize(small) mcolor(blue%98) lw(medthick)) ///
        (rcap upper lower con, lw(medthin) lcolor(blue%98) msize(medium) horizontal), ///
        xtitle("Coefficient", margin(small) size(*1)) ///
        ytitle(" ", margin(vvsmall) size(*0.8)) ///
        legend(symplacement(north) rows(1) size(small) position(12) ring(1)) ///
        xline(0, lcolor(cranberry)) ///
        xlabel(-0.2(0.1)0.7, labsize(vsmall) format(%2.1f)) ///
        ylabel(, labsize(small) valuelabel) ///
        yscale(range(0.5 5.5)) ///
        xscale(range(-.2 0.71)) ///
        scheme(tab2) xsize(5.5) ysize(3.5) ///
        legend(order(1 "Coefficient" 2 "Upper/Lower 95% CI")) ///
        title("Resilience Index") saving("F3.gph", replace)
restore

preserve
keep if var==3
twoway  (scatter con coef, m(circle) msize(small) mcolor(blue%98) lw(medthick)) ///
        (rcap upper lower con, lw(medthin) lcolor(blue%98) msize(medium) horizontal), ///
        xtitle("Coefficient", margin(small) size(*1)) ///
        ytitle(" ", margin(vvsmall) size(*0.8)) ///
        legend(symplacement(north) rows(1) size(small) position(12) ring(1)) ///
        xline(0, lcolor(cranberry)) ///
        xlabel(-0.2(0.1)0.7, labsize(vsmall) format(%2.1f)) ///
        ylabel(, labsize(small) valuelabel) ///
        yscale(range(0.5 5.5)) ///
        xscale(range(-.2 0.71)) ///
        scheme(tab2) xsize(5.5) ysize(3.5) ///
        legend(order(1 "Coefficient" 2 "Upper/Lower 95% CI")) ///
        title("Food Consumption Score") saving("F4.gph", replace)
restore

preserve
keep if var==4
twoway  (scatter con coef, m(circle) msize(small) mcolor(blue%98) lw(medthick)) ///
        (rcap upper lower con, lw(medthin) lcolor(blue%98) msize(medium) horizontal), ///
        xtitle("Coefficient", margin(small) size(*1)) ///
        ytitle(" ", margin(vvsmall) size(*0.8)) ///
        legend(symplacement(north) rows(1) size(small) position(12) ring(1)) ///
        xline(0, lcolor(cranberry)) ///
        xlabel(-0.2(0.1)0.7, labsize(vsmall) format(%2.1f)) ///
        ylabel(, labsize(small) valuelabel) ///
        yscale(range(0.5 5.5)) ///
        xscale(range(-.2 0.71)) ///
        scheme(tab2) xsize(5.5) ysize(3.5) ///
        legend(order(1 "Coefficient" 2 "Upper/Lower 95% CI")) ///
        title("Empowerment") saving("F5.gph", replace)
restore

preserve
keep if var==5
twoway  (scatter con coef, m(circle) msize(small) mcolor(blue%98) lw(medthick)) ///
        (rcap upper lower con, lw(medthin) lcolor(blue%98) msize(medium) horizontal), ///
        xtitle("Coefficient", margin(small) size(*1)) ///
        ytitle(" ", margin(vvsmall) size(*0.8)) ///
        legend(symplacement(north) rows(1) size(small) position(12) ring(1)) ///
        xline(0, lcolor(cranberry)) ///
        xlabel(-0.2(0.1)0.7, labsize(vsmall) format(%2.1f)) ///
        ylabel(, labsize(small) valuelabel) ///
        yscale(range(0.5 5.5)) ///
        xscale(range(-.2 0.71)) ///
        scheme(tab2) xsize(5.5) ysize(3.5) ///
        legend(order(1 "Coefficient" 2 "Upper/Lower 95% CI")) ///
        title("Log p/c non-farm income") saving("F6.gph", replace)
restore

* Combine and export (Inclusion is now F1)
grc1leg "F1.gph" "F2.gph" "F3.gph" "F4.gph" "F5.gph" "F6.gph", ///
    col(3) ysize(10) xsize(15) scheme(white_brbg) imargin(medsmall) position(12)
graph export "table2zsamescale.png", replace










************************************************************************
*Figure 4 
/**********************************************************************
  Country-by-block effects of MSME selling on incindex3 (z-scored),
  with robust CIs and multi-panel plot.

  Stata 16+
***********************************************************************/

/**********************************************************************
  MSME selling x cultivated-area blocks → incindex3
  - One reghdfe per country, FE (idd + t), cluster SEs
  - Z-scores incindex3 within-country
  - Collects b, 95% CI, N per block; plots with labeled y-axis
  - Panel order in combined graph: ETH, MLW, TZN, UGD, NGR, GHN

  Stata 16+
***********************************************************************/

version 16
clear all
set more off
set linesize 255

*===================== LOAD & PREP =====================*
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear

* where to save graphs
local outdir "`c(pwd)'"   // change if desired

* FE/cluster ids
global idd   "idd"
global clust "cll"        // used only for GHN below

drop if inlist(t,1,2,3) & country=="TZN"

* vars hygiene
capture rename road_density road_dense

* ensure cultivated-area variable is named blocks, numeric with value labels
capture confirm variable blocks
if _rc {
    capture confirm variable block
    if !_rc {
        rename block blocks
    }
}
capture confirm string variable blocks
if !_rc {
    di as txt "Encoding string 'blocks' → numeric with value labels"
    encode blocks, gen(__blocks_num)
    drop blocks
    rename __blocks_num blocks
}

* treatment & controls
capture drop treat1
gen byte treat1 = 0
replace treat1 = 1 if cci>0 & cci<.

capture drop sell_msme
gen byte sell_msme = (treat1==1 | ac_ent==1)
replace  sell_msme = . if treat1==. & ac_ent==.

capture drop farmsize2
gen double farmsize2 = farmsize*farmsize

global cont "agehead female ac_workforce dependency_ratio hhsize farmsize farmsize2 NonfIncShare road_dense"
global out  "incindex3"

*===================== POSTFILE =====================*
tempname posth
tempfile results
postfile `posth' str3 country ///
                 double blk ///
                 str24 blklab ///
                 double coef lower upper ///
                 long N using "`results'", replace

*===================== HELPER PROGRAM =====================*
capture program drop _grab_block_ci
program define _grab_block_ci, rclass
    syntax , K(integer)

    local tcrit = invttail(e(df_r), 0.025)

    capture local b  = _b[`k'.blocks#c.sell_msme]
    if _rc local b = .
    capture local se = _se[`k'.blocks#c.sell_msme]
    if _rc local se = .

    local lo = cond(missing(`b') | missing(`se'), ., `b' - `tcrit'*`se')
    local hi = cond(missing(`b') | missing(`se'), ., `b' + `tcrit'*`se')

    return scalar b  = `b'
    return scalar lo = `lo'
    return scalar hi = `hi'
end

*===================== COUNTRY LOOPS =====================*
local main_countries "ETH MLW NGR TZN UGD"
local ghana "GHN"

foreach cc of local main_countries {
    preserve
    keep if country=="`cc'"
    count
    if r(N)==0 {
        di as err "No rows for `cc' after filters; skipping."
        restore
        continue
    }

    quietly summarize incindex3 if !missing(incindex3)
    if r(N)>0 & r(sd)>0 {
        replace incindex3 = (incindex3 - r(mean))/r(sd)
    }
    else if r(N)>0 {
        replace incindex3 = incindex3 - r(mean)
    }

    di as res "Running reghdfe for `cc' (cluster=`$idd') ..."
    reghdfe $out c.sell_msme#i.blocks $cont, absorb($idd t) vce(cluster $idd)

    levelsof blocks, local(levels)
    di as txt "  blocks present: `levels'"

    foreach k of local levels {
        count if blocks==`k'
        local N = r(N)

        _grab_block_ci, k(`k')
        local b  = r(b)
        local lo = r(lo)
        local hi = r(hi)

        * try to read the human label for this block
        local blab : label (blocks) `k'
        if "`blab'"=="" local blab = string(`k')

        di as txt "    block=`k' (`blab')  N=`N'  b=" %6.3f `b' "  [" %6.3f `lo' ", " %6.3f `hi' "]"

        post `posth' ("`cc'") (`k') ("`blab'") ///
                      (`b') (`lo') (`hi') (`N')
    }
    restore
}

foreach cc of local ghana {
    preserve
    keep if country=="`cc'"
    count
    if r(N)==0 {
        di as err "No rows for `cc' after filters; skipping."
        restore
        continue
    }

    quietly summarize incindex3 if !missing(incindex3)
    if r(N)>0 & r(sd)>0 {
        replace incindex3 = (incindex3 - r(mean))/r(sd)
    }
    else if r(N)>0 {
        replace incindex3 = incindex3 - r(mean)
    }

    di as res "Running reghdfe for `cc' (cluster=`$clust') ..."
    reghdfe $out c.sell_msme#i.blocks $cont, absorb($clust t) vce(cluster $clust)

    levelsof blocks, local(levels)
    di as txt "  blocks present: `levels'"

    foreach k of local levels {
        count if blocks==`k'
        local N = r(N)

        _grab_block_ci, k(`k')
        local b  = r(b)
        local lo = r(lo)
        local hi = r(hi)

        local blab : label (blocks) `k'
        if "`blab'"=="" local blab = string(`k')

        di as txt "    block=`k' (`blab')  N=`N'  b=" %6.3f `b' "  [" %6.3f `lo' ", " %6.3f `hi' "]"

        post `posth' ("`cc'") (`k') ("`blab'") ///
                      (`b') (`lo') (`hi') (`N')
    }
    restore
}

postclose `posth'

*===================== PLOTTING DATA =====================*
use "`results'", clear
order country blk blklab coef lower upper N
sort country blk

* Map your exact block text → fixed Y order (so labels always show)
gen byte y = .
replace y = 1 if blklab=="0 - 0.25 ha"
replace y = 2 if blklab=="0.25 - 1 ha"
replace y = 3 if blklab=="1 - 3 ha"
replace y = 4 if blklab=="3 - 5 ha"
replace y = 5 if blklab=="> 5 ha"

label define ylbl 1 "0 - 0.25 ha" 2 "0.25 - 1 ha" 3 "1 - 3 ha" 4 "3 - 5 ha" 5 "> 5 ha", replace
label values y ylbl
label var y "Cultivated Area"

*===================== GRAPH PER COUNTRY =====================*
cap which grc1leg
if _rc ssc install grc1leg

* Pretty country names for titles
local cname_ETH "Ethiopia"
local cname_MLW "Malawi"
local cname_TZN "Tanzania"
local cname_UGD "Uganda"
local cname_NGR "Nigeria"
local cname_GHN "Ghana"

* Desired panel order (left→right, top→bottom)
local order "ETH MLW TZN UGD NGR GHN"
local saved ""

foreach cc of local order {
    preserve
    keep if country=="`cc'"
    keep if inrange(y,1,5)
    count if !missing(coef)
    if r(N)==0 {
        di as err "Skipping `cc' — no non-missing coefficients."
        restore
        continue
    }

    * Resolve pretty title
    local title = "`cname_`cc''"

    * Blue points + Blue CI; x-axis title just "Coefficient"
    twoway ///
        (scatter y coef, m(circle) mcolor(blue) msize(small) lw(medthick)) ///
        (rcap upper lower y, lcolor(blue) lw(medthin) horizontal), ///
        xtitle("Coefficient", margin(small)) ///
        ylabel(1/5, valuelabel angle(0) labsize(small)) ///
        xline(0, lcolor(cranberry)) ///
        legend(order(1 "Coefficient" 2 "95% CI") rows(1) pos(12) ring(1)) ///
        scheme(tab2) xsize(5.5) ysize(3.5) ///
        title("`title'") saving("`outdir'\S_`cc'.gph", replace)

    local saved `"`saved' "`outdir'\S_`cc'.gph""'
    restore
}

*===================== COMBINE IN REQUESTED ORDER =====================*
capture confirm file "`outdir'\S_ETH.gph"
if !_rc {
    grc1leg "`outdir'\S_ETH.gph" ///
            "`outdir'\S_MLW.gph" ///
            "`outdir'\S_TZN.gph" ///
            "`outdir'\S_UGD.gph" ///
            "`outdir'\S_NGR.gph" ///
            "`outdir'\S_GHN.gph", ///
        col(3) ysize(10) xsize(15) scheme(white_brbg) imargin(medsmall) position(12)

    * graph export "`outdir'\Figure_MSME_Blocks.png", replace
}
else {
    di as err "No graphs were created."
}



************************************************************************
*Figure 5
use "C:\Users\andre\OneDrive\Desktop\BMGF\LSMS ISA\MAP\Data Fred\Panel\panel_0325-2.dta", clear

global clust 	"cll"
global idd 		"idd"
drop if inlist(t,1,2,3) & country=="TZN"
{

foreach cc in "ETH" "MLW"  "NGR"  "TZN" "UGD" "GHN" {
summ incindex3 if country=="`cc'"
replace incindex3=(incindex3-r(min))/(r(max)-r(min)) if country=="`cc'"
}
*	

global func "lowess"
global func "lpoly"
twoway 	($func incindex3 cluster_alt if country=="MLW" & sell_msme==1,lw(medthin)lcolor(blue%98))			///
		($func incindex3 cluster_alt if country=="MLW" & sell_msme==0,lw(medthin)lcolor(black)lpattern(dash)), 			///
		xtitle("Cluster Index",margin(small)size(*1)) 								///
		ytitle("Inclusion Index",margin(small)size(*1))								///
		legend(symplacement(north) rows(1) size(small) position(12) ring(1)) 		///			
		xlabel(0(0.2)1,labsize(small) format(%4.2f)) 								///
		ylabel(0.1(0.02)0.22,labsize(small) format(%4.2f)) 							///
		yscale(range(0.095 0.225))													///
		scheme(tab2) xsize(5.5) ysize(3.5) 											///
		legend(order(1 "Commercial/MSME" 2 "Non-commercial/non-MSME")) 				///			
		title("Malawi") saving("G1.gph", replace)
twoway 	($func incindex3 cluster_alt if country=="ETH" & sell_msme==1,lw(medthin)lcolor(blue%98))			///
		($func incindex3 cluster_alt if country=="ETH" & sell_msme==0,lw(medthin)lcolor(black)lpattern(shortdash)), 			///
		xtitle("Cluster Index",margin(small)size(*1)) 								///
		ytitle("Inclusion Index",margin(small)size(*1))								///
		legend(symplacement(north) rows(1) size(small) position(12) ring(1)) 		///			
		xlabel(0(0.2)1,labsize(small) format(%4.2f)) 								///
		ylabel(0.1(0.05)0.35,labsize(small) format(%4.2f)) 							///
		yscale(range(0.095 0.36))													///
		scheme(tab2) xsize(5.5) ysize(3.5) 											///
		legend(order(1 "Commercial/MSME" 2 "Non-commercial/non-MSME")) 				///			
		title("Ethiopia") saving("G2.gph", replace)
twoway 	($func incindex3 cluster_alt if country=="UGD" & sell_msme==1,lw(medthin)lcolor(blue%98))			///
		($func incindex3 cluster_alt if country=="UGD" & sell_msme==0,lw(medthin)lcolor(black)lpattern(shortdash)), 			///
		xtitle("Cluster Index",margin(small)size(*1)) 								///
		ytitle("Inclusion Index",margin(small)size(*1))								///
		legend(symplacement(north) rows(1) size(small) position(12) ring(1)) 		///			
		xlabel(0(0.2)1,labsize(small) format(%4.2f)) 								///
		ylabel(0.1(0.05)0.3,labsize(small) format(%4.2f)) 							///
		yscale(range(0.095 0.31))													///
		scheme(tab2) xsize(5.5) ysize(3.5) 											///
		legend(order(1 "Commercial/MSME" 2 "Non-commercial/non-MSME")) 				///			
		title("Uganda") saving("G3.gph", replace)
twoway 	($func incindex3 cluster_alt if country=="TZN" & sell_msme==1,lw(medthin)lcolor(blue%98))			///
		($func incindex3 cluster_alt if country=="TZN" & sell_msme==0,lw(medthin)lcolor(black)lpattern(shortdash)), 			///
		xtitle("Cluster Index",margin(small)size(*1)) 								///
		ytitle("Inclusion Index",margin(small)size(*1))								///
		legend(symplacement(north) rows(1) size(small) position(12) ring(1)) 		///			
		xlabel(0(0.2)1,labsize(small) format(%4.2f)) 								///
		ylabel(0.15(0.05)0.4,labsize(small) format(%4.2f)) 							///
		yscale(range(0.145 0.41))													///
		scheme(tab2) xsize(5.5) ysize(3.5) 											///
		legend(order(1 "Commercial/MSME" 2 "Non-commercial/non-MSME")) 				///			
		title("Tanzania") saving("G4.gph", replace)
twoway 	($func incindex3 cluster_alt if country=="GHN" & sell_msme==1,lw(medthin)lcolor(blue%98))			///
		($func incindex3 cluster_alt if country=="GHN" & sell_msme==0,lw(medthin)lcolor(black)lpattern(shortdash)), 			///
		xtitle("Cluster Index",margin(small)size(*1)) 								///
		ytitle("Inclusion Index",margin(small)size(*1))								///
		legend(symplacement(north) rows(1) size(small) position(12) ring(1)) 		///			
		xlabel(0(0.2)1,labsize(small) format(%4.2f)) 								///
		ylabel(0.1(0.05)0.35,labsize(small) format(%4.2f)) 							///
		yscale(range(0.095 0.355))													///
		scheme(tab2) xsize(5.5) ysize(3.5) 											///
		legend(order(1 "Commercial/MSME" 2 "Non-commercial/non-MSME")) 				///			
		title("Ghana") saving("G5.gph", replace)
twoway 	($func incindex3 cluster_alt if country=="NGR" & sell_msme==1,lw(medthin)lcolor(blue%98))			///
		($func incindex3 cluster_alt if country=="NGR" & sell_msme==0,lw(medthin)lcolor(black)lpattern(shortdash)), 			///
		xtitle("Cluster Index",margin(small)size(*1)) 								///
		ytitle("Inclusion Index",margin(small)size(*1))								///
		legend(symplacement(north) rows(1) size(small) position(12) ring(1)) 		///			
		xlabel(0(0.2)1,labsize(small) format(%4.2f)) 								///
		ylabel(0.2(0.05)0.5,labsize(small) format(%4.2f)) 							///
		yscale(range(0.195 0.505))													///
		scheme(tab2) xsize(5.5) ysize(3.5) 											///
		legend(order(1 "Commercial/MSME" 2 "Non-commercial/non-MSME")) 				///			
		title("Nigeria") saving("G6.gph", replace)
*grc1leg  "G2.gph" "G1.gph" "G6.gph" "G4.gph" "G3.gph" "G5.gph", col(3) ysize(10) xsize(15)scheme(white_brbg) imargin(medsmall) position(6) note("Note: Lowess smoothing. Min-max normalization of inclusion index", size(vsmall))
*graph export "table3b.png", replace 		
}
grc1leg  "G2.gph" "G1.gph" "G6.gph" "G4.gph" "G3.gph" "G5.gph", col(3) ysize(10) xsize(15)scheme(white_brbg) imargin(medsmall) position(6) note("Note: Kernel-weighted local polynomial smoothing. Min-max normalization of inclusion index", size(vsmall))
*graph export "Figure5.png", replace 




************************************************************************
*Figure 5
use panel_0325.dta , clear
global clust 	"cll"
global idd 		"idd"
drop if inlist(t,1,2,3) & country=="TZN"
{

foreach cc in "ETH" "MLW"  "NGR"  "TZN" "UGD" "GHN" {
summ incindex3 if country=="`cc'"
replace incindex3=(incindex3-r(min))/(r(max)-r(min)) if country=="`cc'"
}
*	

global func "lowess"
global func "lpoly"
twoway 	($func incindex3 cluster_alt if country=="MLW" & sell_msme==1,lw(medthin)lcolor(blue%98))			///
		($func incindex3 cluster_alt if country=="MLW" & sell_msme==0,lw(medthin)lcolor(black)lpattern(dash)), 			///
		xtitle("Cluster Index",margin(small)size(*1)) 								///
		ytitle("Inclusion Index",margin(small)size(*1))								///
		legend(symplacement(north) rows(1) size(small) position(12) ring(1)) 		///			
		xlabel(0(0.2)1,labsize(small) format(%4.2f)) 								///
		ylabel(0.1(0.02)0.22,labsize(small) format(%4.2f)) 							///
		yscale(range(0.095 0.225))													///
		scheme(tab2) xsize(5.5) ysize(3.5) 											///
		legend(order(1 "Commercial/MSME" 2 "Non-commercial/non-MSME")) 				///			
		title("Malawi") saving("G1.gph", replace)
twoway 	($func incindex3 cluster_alt if country=="ETH" & sell_msme==1,lw(medthin)lcolor(blue%98))			///
		($func incindex3 cluster_alt if country=="ETH" & sell_msme==0,lw(medthin)lcolor(black)lpattern(shortdash)), 			///
		xtitle("Cluster Index",margin(small)size(*1)) 								///
		ytitle("Inclusion Index",margin(small)size(*1))								///
		legend(symplacement(north) rows(1) size(small) position(12) ring(1)) 		///			
		xlabel(0(0.2)1,labsize(small) format(%4.2f)) 								///
		ylabel(0.1(0.05)0.35,labsize(small) format(%4.2f)) 							///
		yscale(range(0.095 0.36))													///
		scheme(tab2) xsize(5.5) ysize(3.5) 											///
		legend(order(1 "Commercial/MSME" 2 "Non-commercial/non-MSME")) 				///			
		title("Ethiopia") saving("G2.gph", replace)
twoway 	($func incindex3 cluster_alt if country=="UGD" & sell_msme==1,lw(medthin)lcolor(blue%98))			///
		($func incindex3 cluster_alt if country=="UGD" & sell_msme==0,lw(medthin)lcolor(black)lpattern(shortdash)), 			///
		xtitle("Cluster Index",margin(small)size(*1)) 								///
		ytitle("Inclusion Index",margin(small)size(*1))								///
		legend(symplacement(north) rows(1) size(small) position(12) ring(1)) 		///			
		xlabel(0(0.2)1,labsize(small) format(%4.2f)) 								///
		ylabel(0.1(0.05)0.3,labsize(small) format(%4.2f)) 							///
		yscale(range(0.095 0.31))													///
		scheme(tab2) xsize(5.5) ysize(3.5) 											///
		legend(order(1 "Commercial/MSME" 2 "Non-commercial/non-MSME")) 				///			
		title("Uganda") saving("G3.gph", replace)
twoway 	($func incindex3 cluster_alt if country=="TZN" & sell_msme==1,lw(medthin)lcolor(blue%98))			///
		($func incindex3 cluster_alt if country=="TZN" & sell_msme==0,lw(medthin)lcolor(black)lpattern(shortdash)), 			///
		xtitle("Cluster Index",margin(small)size(*1)) 								///
		ytitle("Inclusion Index",margin(small)size(*1))								///
		legend(symplacement(north) rows(1) size(small) position(12) ring(1)) 		///			
		xlabel(0(0.2)1,labsize(small) format(%4.2f)) 								///
		ylabel(0.15(0.05)0.4,labsize(small) format(%4.2f)) 							///
		yscale(range(0.145 0.41))													///
		scheme(tab2) xsize(5.5) ysize(3.5) 											///
		legend(order(1 "Commercial/MSME" 2 "Non-commercial/non-MSME")) 				///			
		title("Tanzania") saving("G4.gph", replace)
twoway 	($func incindex3 cluster_alt if country=="GHN" & sell_msme==1,lw(medthin)lcolor(blue%98))			///
		($func incindex3 cluster_alt if country=="GHN" & sell_msme==0,lw(medthin)lcolor(black)lpattern(shortdash)), 			///
		xtitle("Cluster Index",margin(small)size(*1)) 								///
		ytitle("Inclusion Index",margin(small)size(*1))								///
		legend(symplacement(north) rows(1) size(small) position(12) ring(1)) 		///			
		xlabel(0(0.2)1,labsize(small) format(%4.2f)) 								///
		ylabel(0.1(0.05)0.35,labsize(small) format(%4.2f)) 							///
		yscale(range(0.095 0.355))													///
		scheme(tab2) xsize(5.5) ysize(3.5) 											///
		legend(order(1 "Commercial/MSME" 2 "Non-commercial/non-MSME")) 				///			
		title("Ghana") saving("G5.gph", replace)
twoway 	($func incindex3 cluster_alt if country=="NGR" & sell_msme==1,lw(medthin)lcolor(blue%98))			///
		($func incindex3 cluster_alt if country=="NGR" & sell_msme==0,lw(medthin)lcolor(black)lpattern(shortdash)), 			///
		xtitle("Cluster Index",margin(small)size(*1)) 								///
		ytitle("Inclusion Index",margin(small)size(*1))								///
		legend(symplacement(north) rows(1) size(small) position(12) ring(1)) 		///			
		xlabel(0(0.2)1,labsize(small) format(%4.2f)) 								///
		ylabel(0.2(0.05)0.5,labsize(small) format(%4.2f)) 							///
		yscale(range(0.195 0.505))													///
		scheme(tab2) xsize(5.5) ysize(3.5) 											///
		legend(order(1 "Commercial/MSME" 2 "Non-commercial/non-MSME")) 				///			
		title("Nigeria") saving("G6.gph", replace)
*grc1leg  "G2.gph" "G1.gph" "G6.gph" "G4.gph" "G3.gph" "G5.gph", col(3) ysize(10) xsize(15)scheme(white_brbg) imargin(medsmall) position(6) note("Note: Lowess smoothing. Min-max normalization of inclusion index", size(vsmall))
*graph export "table3b.png", replace 		
}
grc1leg  "G2.gph" "G1.gph" "G6.gph" "G4.gph" "G3.gph" "G5.gph", col(3) ysize(10) xsize(15)scheme(white_brbg) imargin(medsmall) position(6) note("Note: Kernel-weighted local polynomial smoothing. Min-max normalization of inclusion index", size(vsmall))
*graph export "Figure5.png", replace 

